import java.util.Stack;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Hua YY
 * Date: 2024-12-13
 * Time: 19:51
 */
class Solution1_4 {
    public String decodeString(String ss) {
        // 准备工作
        Stack<StringBuffer> str = new Stack<>();
        Stack<Integer> nums = new Stack<>();
        char[] s = ss.toCharArray();
        int n = s.length, i = 0;
        str.push(new StringBuffer());//放一个空串

        // 遍历字符数组并分情况讨论
        while (i < n) {
            // 处理数字的情况
            if (s[i] >= '0' && s[i] <= '9') {
                int tem = 0;
                while (i < n && s[i] >= '0' && s[i] <= '9') {
                    tem = 10 * tem + (s[i] - '0');
                    i++;
                }
                // 处理完放入栈中
                nums.push(tem);
            }else if(s[i] == '['){//处理[]中的字符串,需要拼接一下字符
                i++;
                StringBuffer buffer = new StringBuffer();
                while(i < n && s[i] >= 'a' && s[i] <= 'z'){  //while(s[i] != ']')不能过
                    buffer.append(s[i]);
                    i++;
                }
                str.push(buffer);
            }else if(s[i] == ']'){
                StringBuffer s1 = str.pop();
                int num1 = nums.pop();
                StringBuffer tem = new StringBuffer();
                while(num1 != 0){
                    tem.append(s1);
                    num1--;
                }
                // 这里追加字符要考虑到栈顶为空的情况
                str.peek().append(tem);
                i++;
            }else{//这种情况是字符单独存在，需要直接追加到栈顶元素
                StringBuffer buffer = new StringBuffer();
                while(i < n && s[i] >= 'a' && s[i] <= 'z'){
                    buffer.append(s[i]);
                    i++;
                }
                str.peek().append(buffer);
            }

        }
        return str.pop().toString();
    }
}

public class Test1_4 {
}
